package com.zelo.blog.server.security;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationException;
import org.springframework.stereotype.Component;


/**
 * @description
 * @Auther zhanglu
 * @Date 2017/11/19 上午12:52
 */
@Component
@Slf4j
public class PreAuthUserAuthenticationManager implements AuthenticationManager {
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        AuthenticationUser authenticationUser = (AuthenticationUser) authentication.getPrincipal();
        String token = (String) authentication.getCredentials();
        try {
            if (authenticationUser != null) {
                log.debug("Pre auth token validation successful.");
                return new UsernamePasswordAuthenticationToken(authenticationUser, token, authenticationUser.getRoles());
            } else {
                throw new RememberMeAuthenticationException("Could not validate pre auth token.");
            }
        } catch (Exception ex) {
            throw new AuthenticationServiceException("Error trying to validation pre-auth token.", ex);
        }
    }


}
